package com.rover.system.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rover.system.dao.BaseDao;

@Service
@Transactional
public class RoleResourceService {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private BaseDao  dao;

	@Autowired
	private ResourceService resourceService;

	@Autowired
	private RoleService roleService;

	/*
	 * 根据角色Id获取最小的一个资源id
	 * 
	 * @roles 角色id编号列表
	 */
	// @SuppressWarnings("unchecked")
	// @Transactional(readOnly = true)
	// public Long getFistResourceID(List<Long> roles) {
	// String hql =
	// "select parentId,resource_ID from RoleResource  where role_ID in(:alist) group by parentId,resource_ID order by parentId,resource_ID";
	// Query query = roleResourceDao.getCurrentSession().createQuery(hql);
	// query.setParameterList("alist", roles);
	//
	//
	// if (li.size() <= 0) {
	// return 0l;
	// } else
	// return li.get(0);
	// }

	/*
	 * 根据角色Id获取第一组parentId的resource_ID
	 * 
	 * @roles 角色id编号列表
	 */
	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Integer> getFistResourceID(List<String> roles) {
		//String hql = "select r.parentId,r.id from RoleResource rr,Resource r  where rr.resource_ID=r.id and  rr.role_ID in(:alist) group by r.parentId,r.id order by r.parentId,r.id";
		String hql = "select new list(r.parentId,r.id) from RoleResource rr,Resource r  where rr.resource_ID=r.id and  rr.role_ID in(:alist) group by r.parentId,r.id order by r.parentId,r.id";
//		Query query = roleResourceDao.getCurrentSession().createQuery(hql);
//		query.setParameterList("alist", roles);
		//List<Object[]> li = query.list();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("alist", roles);
		List<Object> li =	(List<Object>)dao.findHql(hql,params);
		List<Integer> liValue = new ArrayList<Integer>();
		
		int iCount = li.size();
		List obj = null;
		// 记录第一条数据parentId的值
		String strFirst = "";
		for (int i = 0; i < iCount; i++) {
			obj = (List)li.get(i);
			if(i==0)
				strFirst = obj.get(0).toString();
			if (strFirst.equals(obj.get(0).toString())) {
				liValue.add(Integer.valueOf(obj.get(1).toString()));
			} else {
				break;
			}
		}
		return liValue;

	}



}
